<template>
  <ContentWrap :show-border="false">
    <SearchBox
      :queryForm="searchList"
      :showExpland="false"
      :showLen="5"
      @update:export-data="handleExport"
      @change-val="handleChange"
      @query="handleSearchQuery"
      @clearDefaultTime="clearDefaultTime"
    />
  </ContentWrap>
  <ContentWrap :show-border="false">
    <div class="flex items-center justify-between">
      <div class="flex items-baseline titbox">
        <div class="text-[16px] text-[#101010] font-semibold mr-[8px] tit">数据概览</div>
        <div class="text-[#999] text-[12px] desc">
          数据每5分钟更新一次
          <!-- 数据每2小时更新，当前统计至2023-02-1620:00 -->
        </div>
        <div class="w-[12px] h-[12px] ml-[4px] cursor-pointer refreshbox" @click="getList">
          <img :src="RefreshPng" class="object-contain w-full h-full" />
        </div>
        <el-button class="ml-[8px]"  @click="handleUpdateAdvertise">更新数据</el-button>
      </div>
      <div class="flex items-center btnbox">
        <el-button type="primary" color="#3721FF" @click="handleImport">导入</el-button>
      </div>
    </div>

    <div class="mt-[24px] w-full flex info">
      <div
        class="rounded-[10px] w-[220px] py-[24px] px-[16px] shrink-0 total"
        :style="`border: 1px solid #f7f7fb;background:url('${Img07Png}') no-repeat right bottom,#fdfdfe;`"
      >
        <div class="flex items-center title">
          <div class="w-[8px] h-[8px] rounded-[50%] circle" style="border: 2px solid #3721ff"></div>
          <div class="text-[#101010] text-[14px] ml-[10px] tit">总广告花费(外币)</div>
        </div>
        <div class="pl-[15px] mt-[4px] flex items-baseline money">
          ￥
          <div class="text-[#101010] font-bold text-[20px] m">
            {{ getIntegerPart(totalInfo?.totalSpend) }}
          </div>
          <div class="text-[#101010] font-bold text-[14px] d">
            .{{ getDecimalPart(totalInfo?.totalSpend) }}
          </div>
          <!-- <div
            class="w-[2px] h-[11px] bg-[#101010] mx-[3px] line"
            style="transform: rotate(15deg); transform-origin: center center"
          ></div>
          <div class="text-[#101010] font-bold text-[14px] o">986.34</div> -->
        </div>
        <!-- <div class="pl-[15px] text-[#999] text-[12px] unit"> 单位$/￥ </div> -->
      </div>

      <div class="ml-[20px] scrollbox" ref="scrollboxRef" style="width: calc(100% - 232px)">
        <div class="flex items-center w-full cursor-pointer srcollRight">
          <div class="flex" ref="scrollRightRef" style="user-select: none; gap: 20px">
            <div
              class="rounded-[10px] w-[220px] py-[24px] px-[16px] shrink-0 total"
              :style="`border: 1px solid #f7f7fb;background:url('${Img08Png}') no-repeat right bottom,#fdfdfe;`"
            >
              <div class="flex items-center title">
                <div class="text-[#101010] text-[14px] ml-[10px] tit">广告花费（$）</div>
              </div>
              <div class="pl-[15px] mt-[4px] flex items-baseline money">
                <div class="text-[#101010] font-bold text-[20px] m">
                  {{ getIntegerPart(totalInfo?.totalSpend) }}
                </div>
                <div class="text-[#101010] font-bold text-[14px] d">
                  .{{ getDecimalPart(totalInfo?.totalSpend) }}
                </div>
              </div>
              <!-- <div class="pl-[15px] text-[#999] text-[12px] unit"> 单位$ </div> -->
            </div>

            <div
              class="rounded-[10px] w-[220px] py-[24px] px-[16px] shrink-0 total"
              :style="`border: 1px solid #f7f7fb;background:url('${Img09Png}') no-repeat right bottom,#fdfdfe;`"
            >
              <div class="flex items-center title">
                <div class="text-[#101010] text-[14px] ml-[10px] tit">展示总次数</div>
              </div>
              <div class="pl-[15px] mt-[4px] flex items-baseline money">
                <div class="text-[#101010] font-bold text-[20px] m">
                  {{ totalInfo?.impressions }}
                </div>
                <!-- <div class="text-[#101010] font-bold text-[14px] d">.00</div> -->
              </div>
              <!-- <div class="pl-[15px] text-[#999] text-[12px] unit"> 单位$ </div> -->
            </div>

            <div
              class="rounded-[10px] w-[220px] py-[24px] px-[16px] shrink-0 total"
              :style="`border: 1px solid #f7f7fb;background:url('${Img10Png}') no-repeat right bottom,#fdfdfe;`"
            >
              <div class="flex items-center title">
                <div class="text-[#101010] text-[14px] ml-[10px] tit">总CPC（$）</div>
              </div>
              <div class="pl-[15px] mt-[4px] flex items-baseline money">
                <div class="text-[#101010] font-bold text-[20px] m">
                  {{ totalInfo?.cpc }}
                </div>
                <!-- <div class="text-[#101010] font-bold text-[14px] d">.00</div> -->
              </div>
              <!-- <div class="pl-[15px] text-[#999] text-[12px] unit"> 单位-- </div> -->
            </div>

            <div
              class="rounded-[10px] w-[220px] py-[24px] px-[16px] shrink-0 total"
              :style="`border: 1px solid #f7f7fb;background:url('${Img11Png}') no-repeat right bottom,#fdfdfe;`"
            >
              <div class="flex items-center title">
                <div class="text-[#101010] text-[14px] ml-[10px] tit">总CPM（$）</div>
              </div>
              <div class="pl-[15px] mt-[4px] flex items-baseline money">
                <div class="text-[#101010] font-bold text-[20px] m">
                  {{ totalInfo?.cpm }}
                </div>
                <!-- <div class="text-[#101010] font-bold text-[14px] d">.00</div> -->
                <!-- <div
                  class="w-[2px] h-[11px] bg-[#101010] mx-[3px] line"
                  style="transform: rotate(15deg); transform-origin: center center"
                ></div>
                <div class="text-[#101010] font-bold text-[20px] m">0</div>
                <div class="text-[#101010] font-bold text-[14px] d">.00</div> -->
              </div>

              <!-- <div class="pl-[15px] text-[#999] text-[12px] unit"> 单位$/￥ </div> -->
            </div>
          </div>
        </div>
      </div>
    </div>
  </ContentWrap>
  <!-- 列表 -->

  <ContentWrap :show-border="false">
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="投放账户" minWidth="240">
        <template #default="{ row }">
          <div class="content-wrap">
            <div>
              广告账户id:
              <el-text type="danger">
                <span class="cursor-pointer" v-copyText="row.advertiserId">{{
                  row.advertiserId
                }}</span>
              </el-text>
            </div>
            <div>
              广告账户名称:
              <el-text type="danger">
                <span class="cursor-pointer" v-copyText="row.advertiserName">{{
                  row.advertiserName
                }}</span>
              </el-text>
            </div>
            <div>
              广告组id:
              <el-text type="danger">
                <span class="cursor-pointer" v-copyText="row.adsetId">{{
                    row.adsetId
                  }}</span>
              </el-text>
            </div>
            <div>
              广告组名称:
              <el-text type="danger">
                <span class="cursor-pointer" v-copyText="row.adsetName">{{
                    row.adsetName
                  }}</span>
              </el-text>
            </div>
          </div>
        </template>
      </el-table-column>
      <!--      <el-table-column label="广告账号id" align="center" prop="advertiserId" />-->
      <!--      <el-table-column label="广告账号名称" align="center" prop="advertiserName" />-->
      <!--      <el-table-column label="广告组id" align="center" prop="adsetId" />-->
      <!--      <el-table-column label="广告组名称" align="center" prop="adsetName" />-->
      <!--      <el-table-column label="商品id" align="center" prop="productId" />-->
      <!--      <el-table-column label="当日时间戳" align="center" prop="thatdayTimestamp" />-->
      <el-table-column label="当日日期" width="120" align="center" prop="thatdayDate" />
      <!--      <el-table-column label="当日总收入" align="center" prop="thatdayTotalAmount" />-->
      <!--      <el-table-column label="当日总支付笔数" align="center" prop="thatdayPaidTotalNum" />-->

      <el-table-column
        label="地区"
        align="center"
        prop="area"
        :filters="filterAreaList"
        :filter-method="filterHandler"
      >
        <template #filter-icon>
          <div class="ml-[10px] mt-[-8px]">
            <Icon icon="ep:filter" :size="12" color="#101010" />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="广告花费（美元）" align="center" prop="spend" />
      <el-table-column label="广告花费（外币）" align="center" prop="spendForeign" />
      <el-table-column label="展示数" align="center" prop="impressions" />
      <el-table-column label="单次点击成本(CPC)" align="center" prop="cpc" />
      <el-table-column label="千展成本(CPM)" align="center" prop="cpm" />
      <el-table-column label="点击数" align="center" prop="clicks" />
      <el-table-column label="点击率" align="center" prop="ctr" />
      <el-table-column label="覆盖人数" align="center" prop="reach" />
      <el-table-column label="部门" align="center" prop="deptName" />
      <el-table-column label="人员" align="center" prop="createName" />
      <el-table-column label="操作" align="center" min-width="120px">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="handleUpdateAdvertise( scope.row )"
          >
          <!-- v-hasPermi="['facebook:adset-everday-cost:update']" -->
            更新数据
          </el-button>
          <!-- <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['facebook:adset-everday-cost:delete']"
          >
            删除
          </el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <AdsetEverdayCostForm ref="formRef" @success="getList" />
  <BatchImport
    ref="batchImportRef"
    :show-dot="true"
    :show-dept="true"
    :deptList="depatList"
    :createList="importCreateNameList"
    width="40%"
    title="导入模板"
    @down-teamplate="downTeamplates"
    @change-dept="handleImportDept"
    @close="isBatchImport = false"
    @confirm="comfirmImport"
  />
</template>

<script setup lang="ts">
import type { TableColumnCtx, TableInstance } from 'element-plus'
import type { TradeOrderQueryVO } from '@/api/mall/trade/order'
import RefreshPng from '@/assets/ad/refresh.png'
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { AdsetEverdayCostApi, AdsetEverdayCostVO } from '@/api/ad/adseteverdaycost'
import AdsetEverdayCostForm from './AdsetEverdayCostForm.vue'
import Img07Png from '@/assets/ad/img07.png'
import Img08Png from '@/assets/ad/img08.png'
import Img09Png from '@/assets/ad/img09.png'
import Img10Png from '@/assets/ad/img10.png'
import Img11Png from '@/assets/ad/img11.png'
import { getSimpleDeptList } from '@/api/system/dept'
import {
  getIntegerPart,
  getDecimalPart,
  throttle,
  buildTree,
  formatTime,
  downTeamplate
} from '@/utils'
import { AppSocialApi } from '@/api/ad/appSocial'
import { getUserPage } from '@/api/system/user'
import { getUserPageNew } from '@/api/member/user'
import { RoiTotalCostVO } from '@/api/ad/roi/types'
import { RoiApi } from '@/api/ad/roi'
import { getGlobeState } from '@/api/publicInterf'
import { usePageLoading } from '@/hooks/web/usePageLoading'
import dayjs from 'dayjs'
const { loadStart, loadDone } = usePageLoading()

const roiTemplateUrl = 'https://qn-cdn-public.daishubobo.com/roidatatemplate.xlsx'

/** facebook广告组每日消耗 列表 */
defineOptions({ name: 'AdsetEverdayCost' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<AdsetEverdayCostVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数

const depatList = ref([])

const createNameList = ref([])

const filterAreaList = ref([])

const importCreateNameList = ref([])

const isBatchImport = ref(false)

const batchImportRef = ref()

const totalInfo = ref<RoiTotalCostVO>({
  adRoi: 0,
  avgAmount: 0,
  avgAmountCny: 0,
  avgSpend: 0,
  avgSpendCny: 0,
  spend: 0,
  thatdayPaidTotalNum: 0,
  thatdayTotalAmount: 0,
  thatdayTotalAmountCny: 0,
  tkSpend: 0,
  totalSpend: 0,
  totalSpendCny: 0,
  impressions: 0,
  cpc: 0,
  cpm: 0
})

// 定义初始化查询参数
const initQuery = {
  pageNo: 1, // 页数
  pageSize: 10, // 每页显示数量
  advertiserId: undefined,
  advertiserName: undefined,
  adsetId: undefined,
  adsetName: undefined,
  productId: undefined,
  thatdayTimestamp: undefined,
  thatdayDate: [],
  thatdayTotalAmount: undefined,
  thatdayPaidTotalNum: undefined,
  area: undefined,
  spend: undefined,
  spendForeign: undefined,
  impressions: undefined,
  cpm: undefined,
  clicks: undefined,
  ctr: undefined,
  cpc: undefined,
  inlineLinkClicks: undefined,
  costPerInlineLinkClick: undefined,
  cpp: undefined,
  reach: undefined,
  frequency: undefined,
  purchaseRoas: undefined,
  deptId: undefined,
  createName: undefined,
  createTime: []
}

// 使用 initQuery 初始化 queryParams
const queryParams = ref({ 
  ...initQuery,
  startDate:dayjs().startOf('day').format('YYYY-MM-DD'), 
  endDate: dayjs().endOf('day').format('YYYY-MM-DD')
 })

const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

const searchList = ref<TradeOrderQueryVO[]>([
  {
    label: '广告账户名称',
    code: 'advertiserName',
    type: 'input'
  },
  {
    label: '广告账户ID',
    code: 'advertiserId',
    type: 'input'
  },

  {
    label: '部门',
    code: 'deptId',
    type: 'treeSelect',
    options: depatList.value
  },
  {
    label: '人员',
    code: 'createName',
    type: 'select',
    options: createNameList.value
  },
  {
    label: '投放时间',
    code: 'thatdayDate',
    type: 'dateRange',
    default:[queryParams.value.startDate,queryParams.value.endDate],
  }
])
const handleSearchQuery = (val) => {
  /***
   * 搜索框查询条件，目前考虑在查询时 queryParams = {...val,pageNo:1,pageSize:10}
   * */
  if (val.thatdayDate && val.thatdayDate.length) {
    val.startDate = val.thatdayDate[0]
    val.endDate = val.thatdayDate[1]
  }
  delete val.thatdayDate
  queryParams.value = { ...initQuery, ...val }
  getList()
  getTotalInfo()
}
/**
 * 汇总信息查询
 */
const getTotalInfo = async () => {
  const queryCondition = JSON.parse(JSON.stringify(queryParams.value))
  delete queryCondition.pageNo
  delete queryCondition.pageSize
  delete queryCondition.createTime
  delete queryCondition.thatdayDate
  queryCondition.type = 1
  console.log(queryCondition, 'queryCondition')
  const res = await RoiApi.getRoiTotalCost(queryCondition)
  totalInfo.value = res
}
const handleChange = (val) => {
  if (val.form.deptId) {
    queryParams.value.deptId = val.form.deptId
  }
}

watch(
  () => queryParams.value.deptId,
  () => {
    if (queryParams.value.deptId) {
      getCreateNameList()
    }
  }
)

const handleImportDept = async (val) => {
  const res = await getUserPageNew({ pageNo: 1, pageSize: 99, deptId: val })
  importCreateNameList.value = res.map((item) => {
    return {
      label: item.id,
      value: item.nickname
    }
  })
}


/**批量更新账户数据*/
const handleUpdateAdvertise = async (row?) => {
  let ids = null,adsetId = null
  if(row){
    ids = row.advertiserId
    adsetId = row.adsetId
  }
  loadStart()
  try {
    loading.value = true
    const res = await AdsetEverdayCostApi.syncCost({ advertiserIds: ids ||'', adsetId, date: queryParams.value.startDate })
    message.success(res)
  } finally {
    loading.value = false
    loadDone()
  }
}

/**
 * 导入
 */
const comfirmImport = async (val: any) => {
  try {
    await AdsetEverdayCostApi.importAdsetEverdayCost(val.file, {
      deptId: val.deptId,
      creator: val.creator,
      createName: val.createName
    })
  } catch (e) {}
}

//查询部门人员
const getCreateNameList = async () => {
  const res = await getUserPage({ pageNo: 1, pageSize: 99, deptId: queryParams.value.deptId })
  createNameList.value = res.list.map((item) => {
    return {
      label: item.nickname,
      value: item.nickname
    }
  })
  searchList.value.map((item) => {
    if (item.code === 'createName') {
      item.options = createNameList.value
    }
  })
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await AdsetEverdayCostApi.getAdsetEverdayCostPage(queryParams.value)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/**
 * 清除默认时间
*/
const clearDefaultTime = () =>{
  searchList.value.forEach(item => {
    if (item.code === 'thatdayDate') {
      item.default = []
    }
  })
}

/**地区筛选*/
const filterHandler = (value: string, row: any, column: TableColumnCtx<any>) => {
  const property = column['property']
  return row[property] === value
}

/**
 * 显示导入
 */
const handleImport = () => {
  batchImportRef.value?.show()
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await AdsetEverdayCostApi.deleteAdsetEverdayCost(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await AdsetEverdayCostApi.exportAdsetEverdayCost(queryParams.value)
    download.excel(data, 'facebook广告组每日消耗.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

// const init = async () => {
//   const [depatRes, appListRes] = await Promise.all([
//     getSimpleDeptList(),
//     AppSocialApi.getAppSocialPage({ pageNum: 1, pageSize: 99 })
//   ])
//   depatList.value = buildTree(depatRes)
//   searchList.value.map((item) => {
//     if (item.code === 'deptId') {
//       item.options = depatList.value
//     }
//   })
// }

/**
 * 下载模板
 */
const downTeamplates = async () => {
  if (roiTemplateUrl) {
    downTeamplate(roiTemplateUrl, '广告数据模板.xlsx')
  }
}

const init = async () => {
  const [depatRes, areaRes] = await Promise.all([
    getSimpleDeptList(),
    getGlobeState({ pageNum: 1, pageSize: 100 })
  ])
  depatList.value = buildTree(depatRes)
  searchList.value.map((item) => {
    if (item.code === 'deptId') {
      item.options = depatList.value
    }
  })
  filterAreaList.value = areaRes.map((item) => {
    return {
      text: item.stateName,
      value: item.stateName
    }
  })
}

/** 初始化 **/
onMounted(() => {
  init()
  getList()
  getTotalInfo()
})
</script>
<style lang="scss" scoped>
.scrollbox {
  overflow-x: auto; /* 允许横向滚动 */
}
:deep(.el-table.myTable thead tr) {
  background-color: #f7f7fb;
  border-radius: 4px;
  overflow: hidden;
}
:deep(.el-table.myTable thead th.el-table__cell) {
  background-color: #f7f7fb;
}
:deep(.el-button) {
  height: 45px !important;
  border-radius: 23px !important;
  padding: 0 22px !important;
}
</style>
